package com.hcb.tonguetiphealth.widget.homepage;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.DBManager;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.LoginActivity;
import com.hcb.tonguetiphealth.view.MoreActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.view.SearchActivity;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class LoginWidget extends GeneralWidget implements OnClickListener {
	
	private Activity ctx;

	private Handler mHandler;
	private ArrayList<ImageView> imageViews ;
//	private LinearLayout llBack;
	private LinearLayout llCity, llSearch, llHotRes, llLogin, llMore ;
	private Button btLogin, btRegesiter;
	private TextView tvUserName, tvPassword;
	private String userName , password; 
	private DBManager db;
	private User user;
	private String strMsg;
	
	public LoginWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.login, this); 
		//db = DBManager.getInstance(ctx);
		bindView();
		bindEvent();
		user = Global.user;
		if (user!=null) {
			mHandler.sendEmptyMessage(MessageWhat.LOGIN_SUCCESS);
		}
	}
	
	private void bindView(){
		//底部按钮
		llCity = (LinearLayout)findViewById(R.id.linearlayout_home_city);
		llSearch = (LinearLayout)findViewById(R.id.linearlayout_home_search);
		llHotRes = (LinearLayout)findViewById(R.id.linearlayout_home_res);
		llLogin = (LinearLayout)findViewById(R.id.linearlayout_home_login);
		llMore = (LinearLayout)findViewById(R.id.linearlayout_home_more);
		//底部按钮
		 
		btLogin = (Button)findViewById(R.id.home_page_login_login_bt);
		btRegesiter = (Button)findViewById(R.id.home_page_login_register_bt);
		
		tvUserName = (TextView)findViewById(R.id.home_page_login_username_et);
		tvPassword = (TextView)findViewById(R.id.home_page_login_password_et);
		
		
		SharedPreferences preferences = ctx.getSharedPreferences(Global.USERNAME,
				0);
		String userName = preferences.getString(Global.USERNAME, "");
		String password = preferences.getString(Global.PASSWORD, "");
		tvUserName.setText(userName);
		tvPassword.setText(password);
//		llBack = (LinearLayout)findViewById(R.id.home_page_login_back);
//		Cursor cursor = db.getCursor(DBManager.table_user);
//		user = new User(cursor);
//		tvUserName.setText(user.getUserName());
//		tvPassword.setText(user.getPassWord());
	}
	
	private void bindEvent(){
		//底部按钮
		llCity.setOnClickListener(this);
		llSearch.setOnClickListener(this);
		llHotRes.setOnClickListener(this);
		llLogin.setOnClickListener(this);
		llMore.setOnClickListener(this);
		//底部按钮
		
		btLogin.setOnClickListener(this);
		btRegesiter.setOnClickListener(this);
		
//		llBack.setOnClickListener(this);
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在登录...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					dismissMessageDialog();
					break;
				case MessageWhat.LOGIN_SUCCESS:
				//	user.setLogin(true);
					System.out.println("suncess-----------");
					Global.user = user;
					SharedPreferences preferences = ctx.getSharedPreferences(Global.USERNAME,
							0);
					SharedPreferences.Editor editor = preferences.edit();
					editor.putString(Global.USERNAME, userName);
					editor.putString(Global.PASSWORD, password);
					editor.commit();
//					showMessage(ctx, "登录成功！");
					ctx.setContentView(new HomepagePersonalWidget(ctx));
					dismissMessageDialog();
					break;
				case MessageWhat.LOGIN_FAILD:
				//	user.setLogin(false);
					dismissMessageDialog();
					showMessage(ctx, strMsg);
					break;
				case MessageWhat.NETWORK_FAILD:
					try {
					  dismissMessageDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					//Toast.makeText(ctx,  "网络有点不给力哦", Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					break;
				}
			}
		};
	}
	
	
	/**
	 * 底部功能菜单按钮点击事件
	 */
	public void onClick(View v) {
		Intent intent = new Intent();
		switch(v.getId()) {
		//底部按钮
		case R.id.linearlayout_home_city:
			break;
		case R.id.linearlayout_home_search:
			intent.setClass(ctx, SearchActivity.class);
			ctx.startActivity(intent);
			ctx.finish();
			break;
		case R.id.linearlayout_home_res:
			break;
		case R.id.linearlayout_home_login:
			intent.setClass(ctx, LoginActivity.class);
			ctx.startActivity(intent);
			ctx.finish();
			break;
		case R.id.linearlayout_home_more:
			intent.setClass(ctx, MoreActivity.class);
			ctx.startActivity(intent);
			ctx.finish();
			break;
			//底部按钮
		case R.id.home_page_login_login_bt:
			doLogin();
			break;
		case R.id.home_page_login_register_bt:
			ctx.setContentView(new RegisterWidget(ctx));
			break;
//		case R.id.home_page_login_back:
//			ctx.finish();
//			break;
		default:
			break;
		}
	}
	
	/**
	 * 按钮触碰事件
	 */
	public void bindTouchEvent(final LinearLayout linearLayout) {
		linearLayout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN) {
					linearLayout.setBackgroundResource(R.drawable.circle_bg);
				} else if (event.getAction() == KeyEvent.ACTION_UP) {
					linearLayout.setBackgroundResource(R.drawable.circle_bg2);
				}
				return false;
			}
		});
	}
	
	 
	private void doLogin(){
		userName = tvUserName.getText().toString();
		password = tvPassword.getText().toString();
		if (userName == null || userName.equals("") || password == null || password.equals("")) {
			showMessage(ctx, "用户名/密码不能为空！");
			return;
		}
		user = new User();
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("username", userName));
				params.add(new BasicNameValuePair("userPassword", password));
				
				String response = HttpUtils.Post(Global.getServletlogin(),
						params);
				if (Global.DEBUG) {
					System.out.println("response" + response);
				}
				if (response != null) {
					try {
						JSONManager jsonManager = new JSONManager();
						if (jsonManager.isGotJSONObject2(response)) {
							JSONObject jsonObject = jsonManager.getJsonObject();
							// System.out.println(strReturn+"sucess");
							user.setUserId(jsonObject.getString("userid"));
							user.setUserName(jsonObject.getString("username"));
							user.setImgUrl(jsonObject.getString("headicon"));
							user.setSex(jsonObject.getString("gender"));
							
							user.setBirthDayTimeInMillis(1000*StringUtils.parseLong(jsonObject.getString("birthday")));
							user.setHeight(jsonObject.getString("height"));
							user.setWeight(jsonObject.getString("weight"));
							user.setCheckedBody(jsonObject.getString("physical"));
							
							user.setLabels(jsonObject.getString("tags"));
							user.setInfo(jsonObject.getString("intro"));
							user.setLevel(StringUtils.parseFloat(jsonObject.getString("level")));
							user.setProvince(jsonObject.getString("province"));
							user.setCity(jsonObject.getString("city"));
							user.seteMail(jsonObject.getString("email"));
							user.setRealName(jsonObject.getString("truename"));
							user.setTel(jsonObject.getString("mobile"));
							
							mHandler.sendEmptyMessage(MessageWhat.LOGIN_SUCCESS);
						} else {
							strMsg = jsonManager.getMsg();
							mHandler.sendEmptyMessage(MessageWhat.LOGIN_FAILD);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						strMsg = "登录失败！";
						mHandler.sendEmptyMessage(MessageWhat.LOGIN_FAILD);
						e.printStackTrace();
					}
				} else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
			}
		}.start();
	}
	
	
	@Override
	public void notifyAdapter() {
		
	}
 
}
